package io.plus.user_interface.io.server;

import io.plus.server.ServerConfiguration;
import io.plus.server.user_interface.ServerAioListener;
import io.plus.user_interface.io.common.Constants;
import io.plus.user_interface.io.common.UserConfiguration;
import io.plus.user_interface.io.common.io;
import io.plus.user_interface.io.server.command.CommandManager;
import io.plus.utils.Threads;
import io.plus.utils.thread.lock_capable_task.DefaultThreadFactory;
import io.plus.utils.thread.lock_capable_task.LockCapableRunnableThreadPoolExecutor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.LinkedBlockingQueue;

@Data
@Slf4j
public class ServerConfigurationImpl extends ServerConfiguration {

    private static int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
    protected LockCapableRunnableThreadPoolExecutor lockCapableRunnableThreadPoolExecutor = null;
    /**
     * IM配置加载类;
     */
    private UserConfiguration userConfiguration;

    public ServerConfigurationImpl(UserConfiguration userConfiguration, ServerAioHandlerImpl serverAioHandlerImpl,
                                   ServerAioListener serverAioListener) {
        super(serverAioHandlerImpl, serverAioListener);
        this.userConfiguration = userConfiguration;
        this.setHeartbeatTimeout(userConfiguration.getHeartbeatTimeout());

        if (this.lockCapableRunnableThreadPoolExecutor == null) {
            LinkedBlockingQueue<Runnable> timQueue = new LinkedBlockingQueue<>();
            String timThreadName = Constants.io;
            this.lockCapableRunnableThreadPoolExecutor = new LockCapableRunnableThreadPoolExecutor(CORE_POOL_SIZE, CORE_POOL_SIZE, Threads.KEEP_ALIVE_TIME,
                    timQueue, DefaultThreadFactory.getInstance(timThreadName, Thread.NORM_PRIORITY), timThreadName);
            this.lockCapableRunnableThreadPoolExecutor.prestartAllCoreThreads();
        }
        userConfiguration.setConfiguration(this);

        CommandManager.init(userConfiguration);
        io.userConfiguration = userConfiguration;
    }


}
